package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DialRenderer;
import org.achartengine.renderer.DialRenderer.Type;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class ApRelevanceTestWidget extends GeneralTestWidget {

    private WlanManager wlanManager;
    private Handler handler;
    private Activity ctx;
    private LinearLayout l;
    private ScrollView sv;
    private LinearLayout chartLayout;
    private static final String TAG = "ApRelevanceTest";
    private Button backBtn;
    private Button btnRetest;
    private boolean connecting;
    private boolean connectEnd = false;
    private int current;
    private int timeout_num;
    private int frequency = 4;
    private float totalTime;
    private double[] xdata;
    private double[] ydata;
    private Task task;
    private String fileName;
    private ImageView pointImageView;
	private CategorySeries category;
	private DialRenderer renderer;
	private GraphicalView mChartView;
	private TextView timesView;
	private TextView timeRateView;
	private TextView sucRateView;
	private float lastcosttime = 0;
	
    public ApRelevanceTestWidget(Activity context) {
        super(context);
        inflate(context, R.layout.aprelevance_test_widget, this);
        this.ctx = context;
        category = new CategorySeries("");
        renderer = new DialRenderer();
        setDialChartAttrs();
        l = (LinearLayout) this.findViewById(R.id.aprelev_test_layout);
        sv = (ScrollView) findViewById(R.id.ap_test_ScrView);
        chartLayout = (LinearLayout) findViewById(R.id.apTestChartLayout);
        backBtn = (Button) findViewById(R.id.ap_test_btnback);
        pointImageView = (ImageView)findViewById(R.id.pointImageView);
        timeRateView = (TextView)findViewById(R.id.timeRateView);
        timesView = (TextView)findViewById(R.id.timesView);
        sucRateView = (TextView)findViewById(R.id.sucRateView);
        timeRateView.setText("0s");
        timesView.setText("0/"+frequency+"次");
        sucRateView.setText("0%");
     //   btnRetest = (Button) findViewById(R.id.btn_retest);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	switch(GlobalApp.nowNetType) {
				case 1:
					backToTestWidget_Wlan(ctx);
					break;
				case 2:
					backToTestWidget_TD(ctx);
					break;
				case 3:
					backToTestWidget_GSM(ctx);
					break;
				default:
					break;
				}
            }
        });
      /*  btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // ApRelevanceTestWidget aw = new ApRelevanceTestWidget(ctx);
                // ctx.setContentView(aw);
                // aw.scanWifi();
                if (null != fileName) {
          //          new UploadResultTask().execute();           ///////////////
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
            }
        });*/
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    dismissMessageDialog();
                    wlanManager.stopScan();
                    testWidget = "ApRelevanceTestWidget";
                    showWifiListDialog(ctx, wlanManager, handler);
                    testWidget = "";
                    break;
                case MessageWhat.WIFI_SELECTED:
                    start(selectedScanResult);
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissMessageDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                default:
                    update(msg.what);
                }
            }
        };
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler);
        task = new Task();
      //  buildDialChart();
      //  mChartView.invalidate();
    }

    protected void scanWifi() {
        showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    private final class ApTestThread extends Thread {
        private ScanResult scan;

        public ApTestThread(final ScanResult scan) {
            this.scan = scan;
        }

        @Override
        public void run() {
        	executable = true;
            while (current < frequency && executable) {
                if (!connecting) {
                    current++;
                    connecting = true;
                    wlanManager.connect(scan);
                    startConnectTimeoutListener();
                }
                if(!connectEnd){
                	connectEnd = true;
                    WifiInfo  wifiInfo = wlanManager.getCurrentNetwork();
                    SupplicantState span = (SupplicantState) wifiInfo.getSupplicantState();
                    int temp1 = span.describeContents();
                    SupplicantState temp2 = span.UNINITIALIZED;
                    SupplicantState temp3 = span.ASSOCIATED;
                    SupplicantState temp4 = span.ASSOCIATING;
                    SupplicantState temp5 = span.COMPLETED;
                    SupplicantState temp6 = span.DISCONNECTED;
                    SupplicantState temp7 = span.ASSOCIATED;

                    System.err.println(temp1+":describeContents()");
                    System.err.println(temp2+":describeContents()");
                    
                }
                try {
                	System.out.println(current + " -------- ApTestThread");
					Thread.sleep(500);
				} catch (InterruptedException e) {}
            }
        }

    }

    private void start(final ScanResult scan) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            xdata = new double[frequency];
            ydata = new double[frequency];
            final ApTestThread apTestThread = new ApTestThread(scan);
         //   this.showProgressDialog(ctx, "正在进行AP关联测试...", frequency);
            try {
                initTask(task, ctx, ConnectivityManager.TYPE_WIFI);
			} catch (Exception e) {
				System.err.println(e+"==========================");
			//	showMessage(ctx,"任务初始化失败:"+e);
			}

            task.startTime = StringUtils.getDateTime();
            apTestThread.start();
        }
    }

    private void startConnectTimeoutListener() {
        TimerTask wifiReceiverTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    Log.e(TAG, "AP关联第" + current + "测试连接超时");
                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);
    }

    void update(int what) {
   //     setDialogProgress(current);
        switch (what) {
        case MessageWhat.WIFI_SUCESS_CONNECTED:
            if (connecting) {
                float costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / (float)1000;
                xdata[current - 1] = current;
                ydata[current - 1] = costTime;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次关联AP点：");
                s.append(wlanManager.getCurrentScanResult().SSID)
                .append("\n MAC地址：").append(wlanManager.getCurrentScanResult().BSSID);
                s.append("\n IP：").append(wlanManager.getIpAddress())
                .append("  时间：").append(costTime).append(" s");
                totalTime += costTime;
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv);
                
                if (current == frequency) {
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
                DecimalFormat df1 = new DecimalFormat("#0.000");
                timeRateView.setText(df1.format((float) (totalTime / frequency)));
                timesView.setText(current+"/"+frequency+"次");
                sucRateView.setText(String.valueOf((float) ( frequency - timeout_num) / frequency * 100)+"%");
                rotateDialChart(costTime);
                connecting = false;
                connectEnd = true;
            }
            break;
        case MessageWhat.WIFI_CONNECT_TIMEOUT:
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次关联 AP点：");
            s.append(wlanManager.getCurrentScanResult().SSID)
            .append("\n MAC地址：").append(wlanManager.getCurrentScanResult().BSSID).append("  失败.");
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            l.addView(tv);
            setTimeoutNum(1);
            connectEnd = true;
            if (current == frequency) {
                wlanManager.sendMsg(MessageWhat.DONE);
            }
            DecimalFormat df1 = new DecimalFormat("#0.000");
            timeRateView.setText(df1.format((float) (totalTime / frequency)));
            timesView.setText(current+"/"+frequency+"次");
            sucRateView.setText(String.valueOf((float) ( frequency - timeout_num) / frequency * 100)+"%");
         //   rotateDialChart(costtime);
            connecting = false;
            break;
        case MessageWhat.DONE:
            s = new StringBuffer();
            int success = frequency - timeout_num;
            DecimalFormat df = new DecimalFormat("#0.000");
            float temp = (float) (totalTime / frequency); 
            s.append("关联测试次数：").append(frequency);
            s.append("  关联成功次数：").append(success).append('\n');
            s.append("关联成功率：").append((float) success / frequency * 100).append('%');
            s.append("  关联平均时延：").append(df.format(temp)).append('s');
            tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.CYAN);
            tv.setText(s);
            l.addView(tv);
            drawChart();
            
            task.endTime = StringUtils.getDateTime();
            task.relevanceAPAvgTime = df.format((float) (totalTime / frequency));
            task.relevanceAPSuccessRate = String.valueOf((float) success / frequency * 100);
            
            this.dismissProgressDialog();
            connecting = false;
            break;
        }
        setScrollViewDown(sv);
    }

    private void drawChart() {
    	int max =getMax(ydata);
    	ChartManager cm = new ChartManager(ctx, 6, max);
    	
        //ChartManager cm = new ChartManager(ctx, 5, 50);
        String chartTitle = "AP关联测试";
        String[] lineTitles = new String[] { "AP关联时间" };
        List<double[]> x = new ArrayList<double[]>(1);
        List<double[]> y = new ArrayList<double[]>(1);
        x.add(xdata);
        y.add(ydata);
        int[] colors = new int[] { Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        chartLayout.addView(lineChart);
        
    //    new UploadResultTask().execute();               ///////////////////////
    }

    private void setTimeoutNum(int timeout_num) {
        this.timeout_num += timeout_num;
    }
    
    private class UploadResultTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            showMessage(ctx, "正在上传结果...");
        }

        @Override
        protected String doInBackground(Void... params) {
            
            if (fileName == null) {
                TaskParser parser = new PullTaskParser();
                fileName = parser.XmlFileCreator(task);
            }
            if (uplod(fileName, ctx, handler)) {
                fileName = null;
            } 
            return fileName;
        }
/*
        protected void onPostExecute(String result) {
            if (result == null) {
                showMessage(ctx, "上传成功.");
            }
        }*/
    }
    
    public void buildDialChart(){
    	 if (mChartView == null) {
   	      LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
   	      mChartView = ChartFactory.getDialChartView(ctx, category, renderer);
   	      layout.addView(mChartView, new LayoutParams(
   	      LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }else {
   	      mChartView.setBackgroundResource(R.id.chart);
   	      mChartView.repaint();
        }
    }
    
    public void setDialChartAttrs(){
    	 category.add("Current", 0);//给仪表一个初始值，不然报错
         
         renderer.setChartTitleTextSize(20);
         renderer.setLabelsTextSize(15);
         renderer.setLegendTextSize(15);//说明字体的大小
         SimpleSeriesRenderer r = new SimpleSeriesRenderer();
         r.setColor(Color.RED);//指针的颜色
         renderer.setMargins(new int[] { 20, 30, 15, 20 });//设置图表的外边框(上/左/下/右)  

         renderer.addSeriesRenderer(r);
         renderer.setLabelsTextSize(8);//仪表盘字体大小
         renderer.setLabelsColor(Color.GREEN);//仪表盘格子的颜色
         renderer.setShowLabels(true);
         //设置指针样式（默认为三角形）此为箭头
         renderer.setVisualTypes(new DialRenderer.Type[] {Type.ARROW});
         renderer.setMinValue(0);//仪表盘最小值
         renderer.setMaxValue(100);//仪表盘最大值
    }
    public void rotateDialChart(float costtime){
    		
    		float start = lastcosttime;
    		float end = 0;
    		if(costtime >=0 && costtime < 5){
    			end = costtime/1 * 18;
    		}else if(costtime >=5 && costtime <30) {
    			end = 5 *18 + (costtime-5)/5 *18;
			}else if(costtime >=30){
				end = 180f;
			}
    		lastcosttime = end;
    	// 旋转动画效果 
			 AnimationSet animation=new AnimationSet(true);
			 RotateAnimation rotateAnimation=new RotateAnimation(start, end,
					Animation.RELATIVE_TO_SELF, 1f,
					Animation.RELATIVE_TO_SELF, 0.25f);
		//	AlphaAnimation alpha=new AlphaAnimation(1, 0);
			/* ScaleAnimation acale=new ScaleAnimation(1, 0.1f, 1,0.1f,
					 Animation.RELATIVE_TO_SELF, 0.5f,
					 Animation.RELATIVE_TO_SELF, 0.5f);
				acale.setDuration(1000);
				animation.addAnimation(acale);*/
			 rotateAnimation.setDuration(10);
			 animation.addAnimation(rotateAnimation);
			 animation.setFillEnabled(true);
			 animation.setFillAfter(true);
		//	 alpha.setDuration(3000);
		//	 animation.addAnimation(alpha);
			 pointImageView.startAnimation(animation); 
		}
}
